/**
 * 测试用编辑接口测试用例
 *
 * Created by raquelmao on 2020/06/10.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/run-tests/self_designed');

module.exports = describe('/PUT tests/:id.json', function () {
  const administrator = new Administrator();
  let project = {};
  const newUserIds = [];
  function url(testId) {
    return `/tests/${testId}.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((res) => {
        project = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'put');
  common.should.be.tester(uri, url, 'put');

  // 正常编辑测试用例
  it('it should EDIT test', function (done) {
    let projectVersion;
    let test;
    let key = randomstring.generate(8);
    const newValue = randomstring.generate(5);
    project.createRandomVersion()
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllTests(benchmark);
      })
      .then((res) => {
        [test] = res;
        key = test.getFieldKeys(test.data)[0] || key;
        return project.creator.login();
      })
      .then(() => {
        chai.request(uri)
          .put(url(test.testId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .send({ key, value: newValue })
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.testCaseMessage(res.body);
            const path = key.split('.');
            let { data } = res.body;
            for (let i = 0; i < path.length; i += 1) {
              data = data[path[i]];
            }
            data.should.be.eql(newValue);
            done();
          });
      })
      .catch(done);
  });
});
